'''
Created on Oct 21, 2009

@author: kage
'''
import os, subprocess, re

class MuxBase:
    q='"'
    def __init__(self, args=None):
        self.mkvMergePath = args['mkvMergePath']
        self.mkvExtractPath = args['mkvExtractPath']
        self.priority = args['priority']
    
        self.__execute = ''
        self.__completedFlag = False
        self.__successFlag = False
        self.__time_taken = 0
        self.__message = ''
        
        #auxillary convenience data
        self.__p = re.compile('\d+')
    
    def resetStatus(self):
        self.__execute = ''
        self.__completedFlag = False
        self.__successFlag = False
        self.__time_taken = 0
        self.__message = ''
    
    def muxOperation(self):
        
        #execution
        # TODO check this code
        #self.__f = open("temp.bat", 'w')
        #self.__f.write(self.__execute)
        #self.__f.close()
        
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        self.__process = subprocess.Popen(str(self.__execute), stdout=subprocess.PIPE, startupinfo=startupinfo)
        self.__run_log = self.__process.communicate()
        
        #processing output
        if(self.__run_log[1] == None and "Progress: 100%" in self.__run_log[0]):
            self.__successFlag = True
            self.__time_taken = self.__getTimeTaken()
        else:
            self.__message = self.__run_log[0]
            self.__successFlag = False
            
        #cleanup and wrap-up
        self.__completedFlag = True
    
    def setCommandLine(self,data):
        self.__execute = data
    
    def getCommandLine(self):
        return self.__execute
    
    def completed(self):
        return self.__completedFlag
    def success(self):
        return self.__successFlag
    def errorCode(self):
        return self.__message
    def runTime(self):
        return self.__time_taken
    
    def __getTimeTaken(self):
        lines = self.__run_log[0].split('\n')
        __result = 0
        for x in lines:
            if("Muxing took" in x and "seconds" in x):
                __result = int(self.__p.findall(x)[0])
                break
        return __result
